# -*- coding: utf-8 -*-
__author__ = 'jiangzhenfeng'

import json
import os, commands
import time

INTERFACE_FILE_INFO = ""
IMPLEMENTATION_FILE_INFO = ""
CLASS_NAME_INFO = "@class "
CLASS_INPUT_NAME = ""

# 读取用户文件目录输入
def read_file_name():
    file_name = raw_input('请输入json文件目录，以.json 结尾,文件内容样式为\n{\n  \"content:\"{ '
                          '}\n}\n '
                          '\n')
    file_name = file_name.replace(" ", "")
    while file_name:
        if file_name.endswith('.json'):
            break
        else:
            print('Your file path is not end of \'.josn\'!')
            file_name = raw_input('请输入json文件目录，以.json 结尾,文件内容样式为\n{\n  \"content:\"{ '
                          '}\n}\n '
                          '\n')

    if (file_name):
        print('Your file path is %s' % file_name)
        return file_name
    return None

def read_Model_name():
    file_name = raw_input('请输入 Model 名:\n')
    while len(file_name) < 1:
        file_name = raw_input('请输入 Model 名:\n')

    return file_name


# 校验并加载json文件
def read_json_content_info(path):
    with open(path, 'r') as file_info:
        try:
            info_data = json.load(file_info)
            content_data = info_data['content']
            return content_data
        except Exception as e:
            print(e)


# 处理json中键值对 dict
def process_dict_info(dict_data, model_name):
    if len(dict_data.keys()) < 1:
        raise None

    fileStr_h = "\n\n\n@interface %s : NSObject\n\n" % model_name
    fileStr_m = "\n\n@implementation %s \n" % model_name
    global INTERFACE_FILE_INFO
    global CLASS_INPUT_NAME
    global IMPLEMENTATION_FILE_INFO
    global CLASS_NAME_INFO

    for key_str in dict_data.keys():
        obj_value = dict_data[key_str]
        if isinstance(obj_value,int):
            pro = '@property(nonatomic,strong) NSNumber *%s;\n' % key_str
            fileStr_h = fileStr_h + pro

        elif isinstance(obj_value,str) or isinstance(obj_value, unicode):
            pro = '@property(nonatomic,copy) NSString *%s;\n' % key_str
            fileStr_h = fileStr_h + pro

        elif isinstance(obj_value, list):
            pro = '@property(nonatomic,strong) NSArray <%s *> * %s;\n' % ((model_name+'_'+key_str),
                key_str)
            fileStr_m = fileStr_m + "\n+ (NSDictionary " \
                                    "*)mj_objectClassInArray {\n"
            fileStr_m = fileStr_m + "    return @{@\"%s\":[%s class]};" % (
                key_str, (model_name+'_'+key_str)) + "\n}\n"
            fileStr_h = fileStr_h + pro
            tmp_list_str = process_list_info(obj_value, model_name+'_'+key_str)[0]
            INTERFACE_FILE_INFO = INTERFACE_FILE_INFO + tmp_list_str

        elif isinstance(obj_value, dict):
            pro = '@property(nonatomic,strong) %s * %s;\n' % \
                  ((model_name+'_'+key_str), key_str)
            fileStr_h = fileStr_h + pro
            tpm_dict_str, tmp_m_str = process_dict_info(obj_value,
                                               model_name+'_'+key_str)
            INTERFACE_FILE_INFO = INTERFACE_FILE_INFO + tpm_dict_str
            IMPLEMENTATION_FILE_INFO = IMPLEMENTATION_FILE_INFO + tmp_m_str

    if cmp(model_name, CLASS_INPUT_NAME) != 0:
        if CLASS_NAME_INFO.endswith('class '):
            CLASS_NAME_INFO = CLASS_NAME_INFO + model_name
        else:
            CLASS_NAME_INFO = CLASS_NAME_INFO + ',' + model_name

    fileStr_h = fileStr_h + "\n@end"
    fileStr_m = fileStr_m + "\n@end"
    return fileStr_h, fileStr_m


# 处理json中数组 Array
def process_list_info(list_data, model_name):
    first_obj = list_data[0]
    fileStr_h = ""
    fileStr_m = ""
    global IMPLEMENTATION_FILE_INFO

    if isinstance(first_obj, int):
        fileStr_h, fileStr_m = process_dict_info({model_name:None}, model_name)

    elif isinstance(first_obj, str) or isinstance(first_obj, unicode):
        fileStr_h, fileStr_m = process_dict_info({model_name: None}, model_name)

    elif isinstance(first_obj, list):
        fileStr_h, fileStr_m = process_list_info(first_obj, model_name)

    elif isinstance(first_obj, dict):
        fileStr_h, fileStr_m = process_dict_info(first_obj, model_name)

    IMPLEMENTATION_FILE_INFO = IMPLEMENTATION_FILE_INFO + fileStr_m

    return fileStr_h, fileStr_m


if __name__ == '__main__':
    path = read_file_name()
    CLASS_INPUT_NAME = read_Model_name()
    # path = '/Users/jiangzhenfeng/Desktop/test.json'
    # CLASS_INPUT_NAME = 'MyTest'

    if path:
        info = read_json_content_info(path)
        dictInfo_h = ""
        dictInfo_m = ""
        if isinstance(info, dict):
            dictInfo_h, dictInfo_m = process_dict_info(info, CLASS_INPUT_NAME)

        elif isinstance(info, list):
            dictInfo_h, dictInfo_m = process_list_info(info, CLASS_INPUT_NAME)

        common_info = "/*\nauto create by model crater " \
                      "machine V1.0\n"
        common_info = common_info + (time.strftime("%Y-%m-%d %H:%M:%S",
                                                   time.localtime()))
        common_info_h = common_info + '\n*/\n\n' + "#import " \
                                                 "<Foundation/Foundation.h>\n\n"
        common_info_m = common_info + '\n*/\n\n' + "#import " \
                                                 "\"%s.h\"" % CLASS_INPUT_NAME

        common_info_h = common_info_h + CLASS_NAME_INFO + ';'
        common_info_h = common_info_h + dictInfo_h
        resultStr_h = common_info_h + INTERFACE_FILE_INFO
        # print(resultStr_h)

        resultStr_m = common_info_m + dictInfo_m
        if len(IMPLEMENTATION_FILE_INFO) > 10:
            resultStr_m = resultStr_m + IMPLEMENTATION_FILE_INFO

        result_dir = commands.getoutput('cd ~/Desktop/ && pwd')
        result_f_h_path = result_dir + '/' + CLASS_INPUT_NAME + '.h'
        result_f_m_path = result_dir + '/' + CLASS_INPUT_NAME + '.m'
        print(result_f_h_path)
        with open(result_f_h_path, 'w') as result_f:
            result_f.write(resultStr_h)

        with open(result_f_m_path, 'w') as result_f:
            result_f.write(resultStr_m)

        os.system('open %s' % result_f_h_path)
        os.system('open %s' % result_f_m_path)

